import style from './style.module.less'
import { Avatar, message } from 'antd'
import React, { useEffect, useState } from 'react'
import * as api from '../../services/api'

export default function GetAvatar(props: any) {
  let token: string = props.token

  const [imgKey, setImgKey] = useState<string>('')
  const [url, setUrl] = useState<string>('')

  useEffect(() => {
    getUserInfo()
  }, [])

  useEffect(() => {
    getImg()
  }, [imgKey])

  async function getImg() {
    try {
      if (imgKey.length > 0) {
        let res = await api.previewFile(imgKey)
        setUrl((window.URL || window.webkitURL).createObjectURL(res.data))
      }
    } catch (e) {
      throw e
    }
  }

  async function getUserInfo() {
    try {
      let res = await api.getUserInfo(token)
      if (res.data.stat === 'ok') {
        setImgKey(res.data.data.avatar)
      } else {
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  return <Avatar className={style.userImg} src={`${url}`} />
}
